package com.vehicle.admin.web.common.shiro.filter;

import com.google.common.collect.Maps;
import com.vehicle.admin.web.common.shiro.token.TokenManager;
import com.vehicle.common.util.WebHelper;
import com.vehicle.ucenter.api.entity.SysUser;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by yantingbin on 2017/7/19.
 */
@Component
public class LoginFilter extends AccessControlFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        SysUser token = TokenManager.getToken();

        if (null != token || isLoginRequest(servletRequest, servletResponse)) {
            return Boolean.TRUE;
        }
        if (WebHelper.isAjax((HttpServletRequest) servletRequest)) {
            Map<String, String> resultMap = Maps.newHashMap();
            resultMap.put("login_status", String.valueOf(HttpServletResponse.SC_MULTIPLE_CHOICES));
            resultMap.put("message", "当前用户未登录");
            WebHelper.out((HttpServletResponse) servletResponse, resultMap);
        }
        return Boolean.FALSE;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        saveRequestAndRedirectToLogin(servletRequest, servletResponse);
        return Boolean.FALSE;
    }
}
